import axios from 'axios';
import storage from './storage.js';
import ZwMessage from './message';

/**
 * 请求拦截器
 */
axios.interceptors.request.use(
    function (config) {
        config.timeout = 60000;
        config.headers['Authorization'] = storage.get('Authorization') || '';
        return config;
    },
    function (error) {
        return Promise.reject(error);
    }
);

/**
 * 封装http请求函数
 * @param {请求名称} name
 * @param {接口入参} data
 */
const request = function (options: any = {}, data = {}) {
    let {
        url,
        method = 'post',
        headers = {
            'content-type': 'application/json'
        },
        pem = false,
        sld = true,
        responseType
    } = options;

    const item: any = {
        pem,
        sld,
        url,
        headers,
        method,
        data,
        responseType
    };

    if (item.method.toUpperCase() === 'GET' || item.method.toUpperCase() === 'DELETE') {
        item.params = item.data;
    }

    return new Promise((resolve, reject) => {
        axios(item)
            .then(resp => {
                successHandler(resp, resolve, reject);
            })
            .catch(err => {
                errorHandler(err.response, reject);
            });
    });
};

/**
 * 接口处理
 * @param resp
 * @param resolve
 */
function successHandler(resp, resolve, reject) {
    if (resp.request.responseType === 'arraybuffer') {
        resolve(resp);
    } else {
        if (resp.config.pem) {
            // 开启pem，页面请求接口自定义处理
            resolve(resp.data);
            return;
        }
        if (resp.data.code === 0) {
            if (resp.data.sub_code === 0) {
                // 如果code和sub_code都为0，直接抛出返回结果
                resolve(resp.data);
            } else {
                // 否则reject抛出信息
                reject(resp);
            }
        } else {
            // 如果code不为0，处理错误异常
            // 401为登录失效，走登录页面
            if ([401].includes(resp.data.code)) {
                if (location.pathname !== '/login') {
                    ZwMessage.error({
                        message: '登录失效，即将为您跳转到登录页…',
                        type: 'error',
                        onClose: () => {
                            location.href = '/login';
                            storage.clear();
                        }
                    });
                }
            } else {
                // 其他错误code走错误提示
                errorHandler(resp);
            }
        }
    }
}

/**
 * 错误接口处理
 * @param error
 */
function errorHandler(resp, reject?: any) {
    if (resp && resp.data) {
        const message = `${resp.data?.message || resp.data?.msg || '系统异常'}`;
        ZwMessage.error(message);
    }
    reject && reject();
}

export default request;
